from paramiko import Transport, Channel
from buffers import Buffers
from configuracoes import Configuracoes
from PyQt4 import QtCore
from threading import Thread
from conexaossh import ConexaoSSH
from time import sleep
import time

import serial

class Testador(QtCore.QObject):
    def __init__(self):
        QtCore.QObject.__init__(self)
        self.config = Configuracoes()
        self.conectadoSSH = False
        self.conectadoSerial = False
        # tempo = time.asctime()
        tempo = time.strftime('%Y-%m-%d--%Hh%Mm%Ss')
        # self.arqserial = 'logs/serial_'+tempo.replace(' ','_').replace(':','-') + '.log'
        # self.arqserver = 'logs/server_'+tempo.replace(' ','_').replace(':','-') + '.log'
        self.arqserial = 'logs/serial_'+tempo+ '.log'
        self.arqserver = 'logs/server_'+tempo+ '.log'
        self.ssh = ConexaoSSH(self.config, self.saidassh, self.arqserver)
        QtCore.QObject.connect(self.ssh, QtCore.SIGNAL("connectsuccess()"), self.conectou)
        QtCore.QObject.connect(self.ssh, QtCore.SIGNAL("connectfailed(PyQt_PyObject)"), self.nconectou)
        self.ultimoarquivo = str(QtCore.QDir.currentPath()) + '/config.ini'

        
    def trocaTimestampSerial(self):
        try:
            self.bufferserial.trocaTimestamp()
            if not self.conectadoSerial:
                raise Exception
        except Exception, e:
            raise Exception
    
    def trocaTimestampSSH(self):
        try:
            self.ssh.bufferssh.trocaTimestamp()
            if not self.ssh.conectado:
                raise Exception
        except Exception, e:
            raise Exception
            
    def conectou(self):
        self.emit(QtCore.SIGNAL("connectsuccess()"))
        

    def nconectou(self, error):
        self.emit(QtCore.SIGNAL("connectfailed(PyQt_PyObject)"),error)
        self.saidassh('Falha na conexao.')

    def conectarserial(self, vel = None):
        self.pegaConfiguracoes()
        try:
            if vel == None:
                self.serial1 = serial.Serial(self.config.ser_porta, int(self.config.ser_speed),timeout=None,xonxoff=0,rtscts=0)
            else:
                self.serial1 = serial.Serial(self.config.ser_porta, vel ,timeout=None,xonxoff=0,rtscts=0)
            self.bufferserial = Buffers(self.saidaserial, self.serial1.read, self.arqserial, self.serial1.inWaiting, 0.1)
        except (Exception), e:
            print e
            self.serial1.close()
            self.conectadoSerial = False
            raise Exception(self.config.ser_porta)
        else:
            self.conectadoSerial = True
            
    def desconectarserial(self):
        self.bufferserial.executar = False
        self.bufferserial.terminate()
        self.serial1.close()
        self.conectadoSerial = False
        self.saidaserial('OK')

    def saidaserial(self, texto):
        self.emit(QtCore.SIGNAL("alteraserial(PyQt_PyObject)"),texto)

    def saidassh(self,texto):
        self.emit(QtCore.SIGNAL("alterassh(PyQt_PyObject)"),texto)
        
    def comandoserial(self,texto):
        self.serial1.write(texto)
        
    def desconectarssh(self):
        self.ssh.desconectar()
        self.saidassh('OK')

    def conectarrastrear(self):
        comando = self.config.rvs_comando +' '+ self.config.rvs_porta +' '+ self.config.rvs_protocolo
        self.ssh.enviaShell(comando)

    def __del__(self):
        self.desconectarssh()

    def pegaConfiguracoes(self):
        self.config = Configuracoes(self.ultimoarquivo)
        
    def abreConfiguracoes(self, arquivo):
        self.ultimoarquivo = str(arquivo)
        self.config = Configuracoes(self.ultimoarquivo)

    def conectarssh(self):
        self.pegaConfiguracoes()
        self.ssh.setconfig(self.config)
        self.ssh.conectar()
